#!/bin/bash

# 此脚本需要在harbor服务器节点执行,检测harbor相关组件的健康状态

# 系统ID
system_id=$(cat config.cnf | grep SystemId | awk -F "=" '{print $2}')
# 告警存放文件夹
alert_dir=$(cat config.cnf | grep AlertDir | awk -F "=" '{print $2}')
# 告警缓存文件
alarm_file_tmp="harbor_check_alarm.txt"
echo -n "" >${alarm_file_tmp}
# 本机ip
local_ip=$(ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")

execute_cycle=$(cat config.cnf | grep ExecuteCycle | awk -F "=" '{print $2}')

# harbor进程状态监控
harbor_addons_check() {
    harbor_addons_name=$(docker ps -a | grep unhealthy | awk '{print $2}' | awk -F ":" '{print $1}')
	if [[ ${harbor_addons_name} != '' ]]; then
		# 进程状态不存在,告警
		for i in $(echo ${harbor_addons_name}); do			
			./gen_alarm.sh -g "容器状态监控" "harbor服务组件状态异常,${i}组件状态unhealthy,IP:$(hostname -I)" 3 "harbor组件" "harbor_pro" ${alarm_file_tmp}
		done
	else
		# 告警存在,恢复原告警
		for i in $(echo ${harbor_addons_name}); do			
			./gen_alarm.sh -r "容器状态监控" "harbor服务组件状态恢复正常,${i}组件状态healthy,IP:$(hostname -I)" "harbor组件" "harbor_pro" ${alarm_file_tmp}
		done
	fi
}

while true; do
    holidays_date=$(cat config.cnf | grep Holidays | awk -F "=" '{print $2}' | sed "s/,/ /g")
	current_date=$(date +'%Y-%m-%d')
	echo $holidays_date | grep -o $current_date >> /dev/null
	if [[ $? -eq 0 ]]; then
		exit 0
	else
		echo -n "" >${alarm_file_tmp}
		harbor_addons_check
		# 将缓存告警放入告警文件夹
		./gen_alarm.sh -s ${alarm_file_tmp}
		sleep ${execute_cycle}
	fi
done
